package cn.com.assistant.controller;

import cn.com.assistant.annotation.AdminLoginToken;
import cn.com.assistant.annotation.PassToken;
import cn.com.assistant.entity.User;
import cn.com.assistant.mapper.UserMapper;
import cn.com.assistant.model.PageDto;
import cn.com.assistant.model.UserLoginModel;
import cn.com.assistant.model.UserPOJO;
import cn.com.assistant.service.UserService;
import cn.com.assistant.utils.RequestUtil;
import cn.com.assistant.utils.ResponseMessage;
import cn.com.assistant.utils.TokenUtil;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import io.swagger.annotations.ApiImplicitParam;
import io.swagger.annotations.ApiImplicitParams;
import io.swagger.annotations.ApiOperation;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.validation.BindingResult;
import org.springframework.web.bind.annotation.*;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpSession;
import javax.validation.Valid;
import java.util.Map;

@RestController
@RequestMapping("/user")
public class UserController {
 
    @Autowired
    UserService userService;
    @Autowired
    UserMapper userMapper;

    @CrossOrigin(origins = "*",maxAge = 3600)
    @PostMapping("/login")
    @ApiOperation(value = "后台用户登录", notes = "后台用户登录")
    @ApiImplicitParam(name = "userLoginModel", value = "后台用户登录模型", required = true, dataType = "UserLoginModel")
    public ResponseMessage login(@RequestBody @Valid UserLoginModel userLoginModel,
                                 HttpServletRequest request) {
        HttpSession session = request.getSession();
        System.out.println("第一次请求");
        return userService.userLogin(userLoginModel.getUsername(), userLoginModel.getPassword(), session);
    }

    @AdminLoginToken
    @CrossOrigin(origins = "*",maxAge = 3600)
    @PostMapping("/userAdd")
    @ApiOperation(value = "添加后台用户", notes = "添加后台用户")
    @ApiImplicitParam(name = "userPOJO", value = "后台用户实体", required = true, dataType = "UserPOJO")
    public ResponseMessage register(@RequestBody @Valid UserPOJO userPOJO, BindingResult bindingResult) {
        if (bindingResult.hasErrors()) {
            return ResponseMessage.validFailResponse().setMsg(bindingResult.getAllErrors());
        }
        try {

            //账号唯一性校验
            ResponseMessage usernameBack = userService.existByUsername(userPOJO.getUsername(), -1);
            if(usernameBack.getStatus().equals(ResponseMessage.FAILED)){
                return ResponseMessage.validFailResponse().setMsg(usernameBack.getMsg());
            }

            //手机号唯一性校验
            ResponseMessage phoneBack = userService.findByPhoneAndIdNot(userPOJO.getPhone(), -1);
            if(phoneBack.getStatus().equals(ResponseMessage.FAILED)){
                return ResponseMessage.validFailResponse().setMsg(phoneBack.getMsg());
            }
        } catch (Exception e) {
            e.printStackTrace();
        }
        return userService.userAdd(userPOJO);
    }

    @AdminLoginToken
    @CrossOrigin(origins = "*",maxAge = 3600)
    @PutMapping("/update")
    @ApiOperation(value = "修改后台用户", notes = "修改后台用户")
    @ApiImplicitParam(name = "userPOJO", value = "后台用户实体", required = true, dataType = "UserPOJO")
    public ResponseMessage userUpdate(@RequestBody @Valid UserPOJO userPOJO, BindingResult bindingResult) {
        if (bindingResult.hasErrors()) {
            return ResponseMessage.validFailResponse().setMsg(bindingResult.getAllErrors());
        }
        try {

            //账号唯一性校验
            ResponseMessage usernameBack = userService.existByUsername(userPOJO.getUsername(), userPOJO.getId());
            if(usernameBack.getStatus().equals(ResponseMessage.FAILED)){
                return ResponseMessage.validFailResponse().setMsg(usernameBack.getMsg());
            }

            //手机号唯一性校验
            ResponseMessage phoneBack = userService.findByPhoneAndIdNot(userPOJO.getPhone(), userPOJO.getId());
            if(phoneBack.getStatus().equals(ResponseMessage.FAILED)){
                return ResponseMessage.validFailResponse().setMsg(phoneBack.getMsg());
            }
        } catch (Exception e) {

        }
        return userService.userUpdate(userPOJO);
    }

    @AdminLoginToken
    @CrossOrigin(origins = "*",maxAge = 3600)
    @DeleteMapping("/delete")
    @ApiOperation(value = "后台用户删除", notes = "后台用户删除")
    @ApiImplicitParam(name = "id", value = "用户id")
    public ResponseMessage userDelete(@RequestParam("id") Integer id) {

        return userService.userDelete(id);
    }

    @AdminLoginToken
    @CrossOrigin(origins = "*",maxAge = 3600)
    @GetMapping("/userDetail")
    @ApiOperation(value = "后台单个用户查询", notes = "后台单个用户查询")
    @ApiImplicitParam(name = "id", value = "用户id")
    public ResponseMessage userDetail(@RequestParam("id") Integer id) {

        return ResponseMessage.defaultResponse().setData(userService.findById(id));
    }

    @AdminLoginToken
    @CrossOrigin(origins = "*",maxAge = 3600)
    @PutMapping("/userPasswordReset")
    @ApiOperation(value = "重置后台用户密码", notes = "重置后台用户密码")
    @ApiImplicitParam(name = "id", value = "用户id")
    public ResponseMessage userPasswordReset(@RequestParam("id") Integer id) {

        return userService.userPasswordReset(id);
    }

    @AdminLoginToken
    @CrossOrigin(origins = "*",maxAge = 3600)
    @PutMapping("/userStatusReset")
    @ApiOperation(value = "修改后台用户状态", notes = "修改后台用户状态")
    @ApiImplicitParams({
            @ApiImplicitParam(name = "id", value = "用户id"),
            @ApiImplicitParam(name = "status", value = "状态")
    })
    public ResponseMessage userStatusReset(@RequestParam("id") Integer id,
                                           @RequestParam(name = "status") Integer status) {

        return userService.userStatusReset(id, status) ;
    }

    @AdminLoginToken
    @CrossOrigin(origins = "*",maxAge = 3600)
    @ApiOperation(value = "客户端用户信息分页列表", notes = "客户端用户信息分页列表")
    @GetMapping(value = "/page")
    public ResponseMessage findByPage(@RequestParam(value = "page", defaultValue = "0") Integer pageNum,
                                      @RequestParam(value = "size", defaultValue = "10") Integer size,
                                      HttpServletRequest request) {
        Map<String, Object> filters = RequestUtil.getParameters(request);
        IPage<User> page = new Page<>(pageNum, size);
        PageDto pageDto = new PageDto();
        pageDto.setUsername(String.valueOf(filters.get("username")));
        pageDto.setPhone(String.valueOf(filters.get("phone")));
        IPage<User> iPage = userMapper.findByPage(page, pageDto);
        return ResponseMessage.defaultResponse().setData(iPage);
    }

    @PassToken
    @CrossOrigin(origins = "*",maxAge = 3600)
    @GetMapping("/noToken")
    public ResponseMessage noToken() {
        return userService.noToken();
    }

    @PassToken
    @CrossOrigin(origins = "*",maxAge = 3600)
    @GetMapping("/noUser")
    public ResponseMessage noUser() {
        return userService.noUser();
    }

    @PassToken
    @CrossOrigin(origins = "*",maxAge = 3600)
    @GetMapping("/expireToken")
    public ResponseMessage expireToken() {
        return userService.expireToken();
    }

    @PassToken
    @CrossOrigin(origins = "*",maxAge = 3600)
    @GetMapping("/illegalToken")
    public ResponseMessage illegalToken() {

        return userService.illegalToken();
    }

    @PassToken
    @CrossOrigin(origins = "*",maxAge = 3600)
    @ApiOperation(value = "后台单个用户查询", notes = "后台单个用户查询")
    @ApiImplicitParam(name = "token", value = "token")
    @GetMapping("/findByToken")
    public ResponseMessage findByToken(@RequestParam("token") String token) {
        return userService.findByToken(token);
    }

    @PassToken
    @CrossOrigin(origins = "*",maxAge = 3600)
    @ApiOperation(value = "获取当前token", notes = "获取当前token")
    @ApiImplicitParam(name = "username", value = "username")
    @GetMapping("/getCurrentToken")
    public ResponseMessage getCurrentToken(@RequestParam("username") String username, HttpServletRequest httpServletRequest) {

        String currentToken = String.valueOf(httpServletRequest.getSession().getAttribute(username + "token"));
        return ResponseMessage.defaultResponse().setData(currentToken);
    }

    @PassToken
    @CrossOrigin(origins = "*",maxAge = 3600)
    @ApiOperation(value = "退出登录", notes = "退出登录")
    @ApiImplicitParam(name = "token", value = "token")
    @GetMapping("/loginOut")
    public ResponseMessage loginOut(@RequestParam("token") String token, HttpServletRequest httpServletRequest) {
        Integer adminUserId = TokenUtil.getAdminUserId(token);
        User adminUser = userMapper.findById(adminUserId);
        HttpSession session = httpServletRequest.getSession();
        session.setAttribute(adminUser.getUsername()+"token", null);
        return ResponseMessage.defaultResponse();
    }

//    @PassToken
//    @CrossOrigin(origins = "*",maxAge = 3600)
//    @GetMapping("/findAll")
//    public ResponseMessage findAll(HttpServletRequest request) {
//        Map<String, Object> filters = RequestUtil.getParameters(request);
//        IPage<User> page = new Page<>(1, 10);
//        PageDto pageDto = new PageDto();
//        pageDto.setUsername(String.valueOf(filters.get("username")));
//        pageDto.setPhone(String.valueOf(filters.get("phone")));
//        IPage<User> byPage = userMapper.findByPage(page, pageDto);
//        return ResponseMessage.defaultResponse().setData(byPage);
//    }

}